<template>
  <div class="profile-container">
    <h2 class="title">个人中心</h2>

    <el-card shadow="hover">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="avatar-container">
            <el-avatar :size="120" :src="form.avatar" />
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleAvatarChange"
            >
              <el-button type="primary" size="small">更换头像</el-button>
            </el-upload>
          </div>
        </el-col>
        <el-col :span="18">
          <el-form :model="form" label-width="100px" style="max-width: 600px;">
            <el-form-item label="用户名">
              <el-input v-model="form.username" disabled />
            </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="form.name" />
            </el-form-item>
            <el-form-item label="入职日期">
              <el-input v-model="form.entryDate" disabled />
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="form.phone" />
            </el-form-item>
            <el-form-item label="职位">
              <el-input v-model="form.positionLabel" disabled />
            </el-form-item>
            <el-form-item label="部门">
              <el-input v-model="form.departmentName" disabled />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveProfile">保存信息</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useAuthStore } from '../stores/auth'
import {
  getEmployeeById,
  updateEmployee,
  indexDepartmentsById,
  uploadFile
} from '../services/auth'
import { ElMessage } from 'element-plus'

const authStore = useAuthStore()

// 职位映射表
const POSITION_MAP = {
  1: '班主任',
  2: '讲师',
  3: '学工主管',
  4: '教研主管',
  5: '咨询师'
}

// 表单数据 - 可编辑字段
const form = ref({
  id: null,
  username: '',
  name: '',
  entryDate: '', // 入职日期
  phone: '',
  job: null, // 职位ID
  positionLabel: '', // 显示用的职位名称
  departmentId: null,
  departmentName: '加载中...',
  avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
  exprList: [] // ✅ 新增字段：员工经历列表
})

// 获取当前用户信息
const fetchUserProfile = async () => {
  try {
    if (!authStore.isAuthenticated || !authStore.user || !authStore.user.id) {
      ElMessage.warning('请先登录')
      router.push({ name: 'Login' })
      return
    }

    const response = await getEmployeeById(authStore.user.id)
    const data = response.data.data

    // ✅ 保存 exprList 到 form 中
    const positionLabel = POSITION_MAP[data.job] || '未知职位'

    form.value = {
      id: data.id,
      username: data.username || '',
      name: data.name || '',
      entryDate: data.entryDate ? formatDate(data.entryDate) : '未知',
      phone: data.phone || '',
      job: data.job,
      positionLabel,
      departmentId: data.deptId,
      departmentName: '加载中...',
      avatar: data.image || form.value.avatar,
      exprList: data.exprList || [] // ✅ 保留原始 exprList 数据
    }

    // 获取部门信息
    if (data.deptId) {
      try {
        const deptRes = await indexDepartmentsById(data.deptId)
        if (deptRes.data.code === 1 && deptRes.data.data?.name) {
          form.value.departmentName = deptRes.data.data.name
        } else {
          form.value.departmentName = '未分配'
        }
      } catch (err) {
        console.error('获取部门信息失败:', err)
        form.value.departmentName = '未分配'
      }
    } else {
      form.value.departmentName = '未分配'
    }
  } catch (error) {
    console.error('获取员工信息失败:', error)
    ElMessage.error('获取员工信息失败')
  }
}

// 时间格式化方法
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 头像上传处理
const handleAvatarChange = async (file) => {
  try {
    const response = await uploadFile(file)
    if (response.data.code === 1) {
      form.value.avatar = response.data.data
      ElMessage.success('头像上传成功')
    } else {
      ElMessage.error('头像上传失败')
    }
  } catch (error) {
    console.error('上传头像异常:', error)
    ElMessage.error('头像上传失败')
  }
}

// 保存员工信息
const saveProfile = async () => {
  try {
    const payload = {
      id: form.value.id,
      name: form.value.name,
      phone: form.value.phone,
      image: form.value.avatar,
      username: form.value.username,

      // ✅ 必须传入的字段
      exprList: form.value.exprList
    }

    await updateEmployee(payload)

    // 更新 Pinia 中的用户信息
    const updatedUser = {
      ...authStore.user,
      name: payload.name,
      phone: payload.phone,
      avatar: payload.image,
      exprList: payload.exprList
    }

    authStore.user = updatedUser
    localStorage.setItem('user', JSON.stringify(updatedUser))

    ElMessage.success('个人信息保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchUserProfile()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.title {
  margin-bottom: 20px;
  color: #2c3e50;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-uploader {
  margin-top: 15px;
}
</style>